package com.hlingsoft.cms.action;

import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.openservices.oss.model.PutObjectResult;
import com.hlingsoft.cms.entity.*;
import com.hlingsoft.cms.entity.vo.AppUserVo;
import com.hlingsoft.cms.entity.vo.NewsVo;
import com.hlingsoft.cms.util.Common;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by selbylei on 2015/5/5.
 */

@Controller
@RequestMapping("/appUser")
public class AppUserAction extends BaseAction {




    private final int rows = 10;

    private final String defaultHeadImageUrl = "http://icake.oss-cn-hangzhou.aliyuncs.com/headImg/default.png";


    /**
     * 验证码
     *
     * @param phone
     * @param request
     * @return
     */
    @RequestMapping(value = "/verifyCode.json", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> verifyCode(
            @RequestParam(value = "phone") String phone,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            String str = Common.Randoms();
            resultMap.put("result", true);
            try {
                List<String> list = new ArrayList<String>();

                VerifyCode verifyCode = verifyCodeDao.getVerifyCodeByPhone(phone);
                Result result = messageService.sendSmsforEvent(phone, str);
                //短信接口请求成功
                if (result.getCode().equals("2")) {
                    //新用户，插入数据表
                    if (verifyCode == null) {
                        VerifyCode verifyCode1 = new VerifyCode();
                        verifyCode1.setPhone(phone);
                        verifyCode1.setCode(str);
                        verifyCode1.setTime(new Date());
                        verifyCodeDao.addVerifyCode(verifyCode1);
                    }
                    //老用户，更新数据表
                    else {
                        verifyCode.setPhone(verifyCode.getPhone());
                        verifyCode.setTime(new Date());
                        verifyCode.setCode(str);
                        verifyCodeDao.updateVerifyCode(verifyCode);
                    }
                    resultMap.put("msg", result.getMsg());
                    resultMap.put("code", result.getCode());
                    resultMap.put("verifyCode", str);
                }
                //手机号码不对
                else if (result.getCode().equals("406")) {
                    resultMap.put("msg", result.getMsg());
                    resultMap.put("code", result.getCode());
                }
                //其他调用短信接口异常
                else {
                    if (verifyCode != null) {
                        resultMap.put("verifyCode", verifyCode.getCode());
                    }
                    resultMap.put("msg", result.getMsg());
                    resultMap.put("code", result.getCode());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("msg", "接口调用失败");
            resultMap.put("result", false);
        }

        return resultMap;

    }


    /**
     * 注册
     * result: 0.失败;0.成功;101.验证码输入有误
     *
     * @param phone
     * @param request
     * @return
     */
    @RequestMapping(value = "/register.json")
    @ResponseBody
    public Map<String, Object> register(
            @RequestParam(value = "phone") String phone,
            @RequestParam(value = "verifyCode") String verifyCode,
            @RequestParam(value = "udId", required = false) String udId,
            @RequestParam(value = "longitude", required = false) Integer longitude,
            @RequestParam(value = "latitude", required = false) Integer latitude,
            @RequestParam(value = "password") String password,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Date now = new Date();
            VerifyCode checkVerifyCode = verifyCodeDao.getVerifyCodeByPhone(phone);
            if (checkVerifyCode == null) {
                resultMap.put("result", false);
                resultMap.put("msg", "请先获取验证码");
            } else {
                if ((checkVerifyCode.getCode()).equals(verifyCode)) {
                    if (appUserDao.getUserByPhone(phone) == null) {
                        AppUser appUser = new AppUser();
                        if (longitude != null) {
                            appUser.setLatitude(longitude.doubleValue());
                        }
                        if (longitude != null) {
                            appUser.setLatitude(latitude.doubleValue());
                        }
                        if (udId != null) {
                            appUser.setUdId(udId);
                        }
                        if (password != null) {
                            appUser.setPassword(password);
                        }
                        String name = phone;
                        String regex = "****";
                        name = name.replaceAll(name.substring(3, 7), regex);
                        name = Common.encodeStr(name);

                        appUser.setPhone(phone);
                        appUser.setName(name);
                        appUser.setNickname(name);
                        appUser.setCreateTime(now);
                        appUser.setUpdateTime(now);
                        appUser.setHeadImage(defaultHeadImageUrl);
                        appUserDao.addAppUser(appUser);

                        //手机新用户，注册时添加对系统账号的关注
                        Focus focus = new Focus();
                        focus.setMyId(appUser.getId());
                        focus.setToId(1);
                        focus.setCreateTime(now);
                        focus.setUpdateTime(now);
                        focusDao.addFocus(focus);
                        resultMap.put("result", true);
                    } else {
                        resultMap.put("msg", "该用户已注册");
                        resultMap.put("result", false);
                    }
                } else {
                    resultMap.put("msg", "验证码输入有误");
                    resultMap.put("result", false);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 登录接口
     *
     * @param udId
     * @param name
     * @param phone
     * @param weChatId
     * @param gender
     * @param signature
     * @param headImage
     * @param longitude
     * @param latitude
     * @param type
     * @param request
     * @return
     */
    @RequestMapping(value = "/login.json")
    @ResponseBody
    public Map<String, Object> login(

            @RequestParam(value = "udId", required = false) String udId,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "weChatId", required = false) String weChatId,
            @RequestParam(value = "gender", defaultValue = "1", required = false) Integer gender,
            @RequestParam(value = "signature", required = false) String signature,
            @RequestParam(value = "headImage", required = false) String headImage,
            @RequestParam(value = "longitude", defaultValue = "0", required = false) Integer longitude,
            @RequestParam(value = "latitude", defaultValue = "0", required = false) Integer latitude,
            @RequestParam(value = "password", required = false) String password,
            @RequestParam(value = "type", defaultValue = "0", required = false) Integer type,  //0.短信登陆 1.微信登陆 2.微博登陆
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {

            //手机用户
            if (type == 0) {
                AppUser user = appUserDao.getUserByPhone(phone);
                //新用户登录
                if (user == null) {
                    resultMap.put("result", false);
                    resultMap.put("msg", "用户未注册");

                } else {
                    //验证码,输入正确
                    if (appUserDao.getUserByPhone(phone).getPassword().equals(password)) {
                        if (udId != null) {
                            user.setUdId(udId);
                        }
                        if (latitude != null) {
                            user.setLatitude(latitude.doubleValue());
                        }
                        if (longitude != null) {
                            user.setLongitude(longitude.doubleValue());
                        }
                        user.setUpdateTime(new Date());
                        appUserDao.updateUser(user);
                        resultMap.put("user", user);
                        resultMap.put("result", true);
                    } else {
                        resultMap.put("result", false);
                        resultMap.put("msg", "密码输入有误");
                    }
                }
            } else {
                AppUser user = appUserDao.getUserByWeChatId(weChatId);
                //新用户
                if (user == null) {
                    user = new AppUser();
                    Date now = new Date();
                    if (udId != null) {
                        user.setUdId(udId);
                    }
                    if (weChatId != null) {
                        user.setWechatId(weChatId);
                    }
                    if (name != null) {
                        user.setName(name);
                        user.setNickname(name);
                    }
                    if (headImage != null) {
                        user.setHeadImage(headImage);
                    }
                    if (gender != null) {
                        user.setGender(gender);
                    }
                    if (signature != null) {
                        user.setSignature(signature);
                    }
                    if (latitude != null) {
                        user.setLatitude(latitude);
                    }
                    if (longitude != null) {
                        user.setLongitude(longitude);
                    }
                    user.setCreateTime(now);
                    user.setUpdateTime(now);
                    if (type != null) {
                        user.setType(type);
                    }
                    appUserDao.addAppUser(user);

                    Focus focus = new Focus();
                    focus.setMyId(user.getId());
                    focus.setToId(1);
                    focus.setCreateTime(now);
                    focus.setUpdateTime(now);
                    focusDao.addFocus(focus);
                }
                //老用户
                else {
                    Date now = new Date();
                    if (udId != null) {
                        user.setUdId(udId);
                    }
                    if (weChatId != null) {
                        user.setWechatId(weChatId);
                    }

                    if (latitude != null) {
                        user.setLatitude(latitude);
                    }
                    if (longitude != null) {
                        user.setLongitude(longitude);
                    }
                    if (type!=null){
                        user.setType(type);
                    }
                    user.setUpdateTime(now);
                    appUserDao.updateUser(user);
                }
                resultMap.put("user", user);
                resultMap.put("result", true);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }

        return resultMap;

    }


    /**
     * 忘记密码
     *
     * @param phone
     * @param verifyCode
     * @param password
     * @param request
     * @return
     */
    @RequestMapping(value = "/getPassword.json")
    @ResponseBody
    public Map<String, Object> getPassword(
            @RequestParam(value = "phone") String phone,
            @RequestParam(value = "verifyCode") String verifyCode,
            @RequestParam(value = "password") String password,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            //获取手机的验证码
            VerifyCode checkVerifyCode = verifyCodeDao.getVerifyCodeByPhone(phone);
            if (checkVerifyCode != null) {
                if ((checkVerifyCode.getCode()).equals(verifyCode)) {
                    //获取用户
                    AppUser checkUser = appUserDao.getUserByPhone(phone);
                    if (checkUser != null) {
                        checkUser.setPassword(password);
                        checkUser.setUpdateTime(new Date());

                        appUserDao.updateUser(checkUser);

                        resultMap.put("result", true);
                    } else {
                        resultMap.put("msg", "用户不存在");
                        resultMap.put("result", false);
                    }
                } else {
                    resultMap.put("msg", "输入正确验证码");
                    resultMap.put("result", false);
                }
            } else {
                resultMap.put("msg", "请输入接收验证的手机号");
                resultMap.put("result", false);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 个人中心详情
     *
     * @param myId
     * @param request
     * @return
     */
    @RequestMapping(value = "/detail.json")
    @ResponseBody
    public Map<String, Object> detail(
            @RequestParam(value = "myId", required = false) Integer myId,
            @RequestParam(value = "toId") long toId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            AppUser appUser = appUserDao.getUserById(toId);
            if (appUser != null) {
                AppUserVo appUserVo = new AppUserVo();
                if (myId != null) {
                    if (focusDao.getFocusByIds(myId, toId) == null) {
                        appUserVo.setIsFocus(0);
                    } else {
                        appUserVo.setIsFocus(1);
                    }
                }
                appUserVo.setIsDR(appUser.getIsDR());
                appUserVo.setHeadImage(appUser.getHeadImage());
                appUserVo.setName(appUser.getName());
                appUserVo.setLevel(appUser.getLevel());
                appUserVo.setSignature(appUser.getSignature());
                appUserVo.setAddress(appUser.getAddress());
                appUserVo.setImageCount(newsDao.getNewsByAppUserIdCount(toId));
                appUserVo.setNickname(appUser.getNickname());
//                appUserVo.setImageCount(imageDao.getImageByAppUserIdCount(toId));
                int fansCount=0;
                if (toId==1){
                   fansCount=focusDao.getFansCount(toId)+42500;
                }else {
                   fansCount=focusDao.getFansCount(toId);
                }
                appUserVo.setFansCount(fansCount);
                appUserVo.setAttentionsCount(focusDao.getAttentionsCount(toId));
                appUserVo.setLikesCount(likesDao.getLikesByAppUserIdCount(toId));
                resultMap.put("appUserVo", appUserVo);
                resultMap.put("result",true);
            } else {
                resultMap.put("msg", "user deleted");
                resultMap.put("result", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 个人中心编辑
     *
     * @param appUserId
     * @param nickname
     * @param gender
     * @param address
     * @param signature
     * @param request
     * @return
     */
    @RequestMapping(value = "/edit.json")
    @ResponseBody
    public Map<String, Object> edit(
            @RequestParam(value = "appUserId") long appUserId,
            @RequestParam(value = "nickname", required = false) String nickname,
            @RequestParam(value = "gender", required = false) Integer gender,
            @RequestParam(value = "address", required = false) String address,
            @RequestParam(value = "signature", required = false) String signature,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            AppUser user = appUserDao.getUserById(appUserId);
            if (user != null) {

                //是否编辑头像
                MultipartFile file = null;
                if (request instanceof MultipartHttpServletRequest) {
                    file = ((MultipartHttpServletRequest) request).getFile("file");
                    String fileName = file.getOriginalFilename();
                    SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String dateString = simpleFormat.format(new Date());
                    putObject(dateString, fileName, file.getInputStream(),
                            file.getSize());
                    String headImage = "http://icake.oss-cn-hangzhou.aliyuncs.com/headImg/" + dateString + "/" + fileName;
                    user.setHeadImage(headImage);
                }

                //是否编辑nickname
                if (nickname != null) {
                    user.setNickname(Common.encodeStr(nickname));
                }

                //是否编辑gender
                if (gender != null) {
                    user.setGender(gender.intValue());
                }

                //是否编辑地址
                if (address != null) {
                    user.setAddress(Common.encodeStr(address));
                }

                //是否编辑signature
                if (signature != null) {
                    user.setSignature(Common.encodeStr(signature));
                }
                user.setUpdateTime(new Date());
                appUserDao.updateUser(user);
                resultMap.put("user", user);
            } else {
                resultMap.put("msg", "此用户不存在");
            }
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }

    /**
     * 我的
     *
     * @param myId
     * @param toId
     * @param type
     * @param request
     * @return
     */
    @RequestMapping(value = "/mine.json")
    @ResponseBody
    public Map<String, Object> mine(
            @RequestParam(value = "myId", required = false) Integer myId, //我
            @RequestParam(value = "toId") long toId,  //查看人的id
            @RequestParam(value = "type") int type,   //0.照片 1.关注 2.粉丝 3.被赞
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            switch (type) {
                case 0: {
                    List<News> newsList = newsDao.getNewsByAppUserId(toId);  //获取toId用户的动态
                    List<NewsVo> newsVoList = new ArrayList<NewsVo>();
                    for (News news : newsList) {
                        List<AppUser> likesUserList = new ArrayList<AppUser>();
                        List<Likes> likesList = likesDao.getLikesByNewsId2(news.getId());
                        for (Likes likes : likesList) {
                            AppUser appUser = appUserDao.getUserById(likes.getMyId());
                            if (appUser != null) {
                                likesUserList.add(appUser);
                            }
                        }
                        AppUser appUser = appUserDao.getUserById(news.getAppUserId());
                        if (appUser != null) {
                            NewsVo newsVo = new NewsVo();
                            newsVo.setId(news.getId());
                            newsVo.setAppUserId(news.getAppUserId());
                            newsVo.setLikesUserList(likesUserList);
                            newsVo.setHeadImageCount(likesUserList.size());
                            newsVo.setContent(news.getContent());

                            List<Image> imageList = imageDao.getImageByNewsId(news.getId());
                            newsVo.setImageList(imageList);
                            Focus focus = focusDao.getFocusByIds(myId, news.getAppUserId());
                            if (focus != null) {
                                appUser.setIsFocus(1);
                            } else {
                                appUser.setIsFocus(0);
                            }
                            if (likesDao.getLikesByNewsId(myId, news.getId()) != null) {
                                newsVo.setIsLikes(1);
                                appUser.setIsLikes(1);
                            } else {
                                newsVo.setIsLikes(0);
                                appUser.setIsLikes(0);
                            }
                            newsVo.setAppUser(appUser);    //活动发布人信息
                            newsVo.setAuthorization(news.getAuthorization());
                            newsVo.setCreateTime(news.getCreateTime());
                            newsVo.setUpdateTime(news.getUpdateTime());
                            newsVo.setCommentCount(commentDao.getCommentByNewsIdCount(news.getId()));
                            newsVoList.add(newsVo);
                        }
                    }
                    resultMap.put("newsVoList", newsVoList);
                    resultMap.put("result", true);
                    break;
                }
                case 1: {
                    List<AppUser> attentionsList = new ArrayList<AppUser>();
                    List<Focus> focusList = focusDao.getAttentionsList(toId); //查看人的关注列表
                    for (Focus focus : focusList) {
                        AppUser attentions = appUserDao.getUserById(focus.getToId());
                        if (attentions!=null){
                            if (myId != null) {
                                if (myId.longValue() != attentions.getId()) {
                                    if (focusDao.getFocusByIds(myId, attentions.getId()) == null) {
                                        attentions.setIsFocus(0);
                                    } else {
                                        attentions.setIsFocus(1);
                                    }
                                } else {
                                    attentions.setIsFocus(1);
                                }

                            } else {
                                attentions.setIsFocus(1);
                            }
                            attentionsList.add(attentions);
                        }

                    }
                    resultMap.put("attentionsList", attentionsList);
                    resultMap.put("result", true);
                    break;
                }
                case 2: {

                    List<AppUser> fansList = new ArrayList<AppUser>();
                    List<Focus> focusList = focusDao.getFansList(toId);   //查看人的粉丝列表
                    for (Focus focus : focusList) {
                        AppUser fans = appUserDao.getUserById(focus.getMyId());
                        if (fans!=null){
                            if (myId != null) {
                                //判断我是否关注了这个粉丝
                                if (myId != fans.getId()) {
                                    if (focusDao.getFocusByIds(myId.longValue(), fans.getId()) == null) {
                                        fans.setIsFocus(0);
                                    } else {
                                        fans.setIsFocus(1);
                                    }
                                } else {
                                    fans.setIsFocus(1);
                                }

                            } else {
                                if (focusDao.getFocusByIds(toId, fans.getId()) == null) {
                                    fans.setIsFocus(0);
                                } else {
                                    fans.setIsFocus(1);
                                }
                            }

                            fansList.add(fans);
                        }
                    }
                    resultMap.put("fansList", fansList);
                    resultMap.put("result", true);
                    break;
                }


                default: {
                    resultMap.put("msg", "请给出正确的类型");
                    resultMap.put("result", false);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 达人申请
     *
     * @param content
     * @param weibo
     * @param wechat
     * @param phone
     * @param request
     * @return
     */
    @RequestMapping(value = "/applyStart.json")
    @ResponseBody
    public Map<String, Object> applyStart(
            @RequestParam(value = "appUserId") long appUserId,
            @RequestParam(value = "content") String content,
            @RequestParam(value = "weibo",required = false) String weibo,
            @RequestParam(value = "wechat") String wechat,
            @RequestParam(value = "phone") String phone,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            AppUser appUser = appUserDao.getUserById(appUserId);
            if (appUser!=null) {
                if (appUser.getIsDR() == 0) {
                    Date now = new Date();
                    Start start = new Start();
                    start.setContent(Common.encodeStr(content));
                    if (weibo!=null){
                        start.setWeibo(weibo);
                    }
                    start.setWechat(wechat);
                    start.setPhone(phone);
                    start.setCreateTime(now);
                    start.setUpdateTime(now);
                    start.setAppUserId(appUserId);
                    startDao.addStart(start);
                    appUser.setIsDR(1);      //更新状态为申请中
                    appUserDao.updateUser(appUser);

                    resultMap.put("start", start);
                    resultMap.put("result", true);
                } else if (appUser.getIsDR() == 1) {
                    resultMap.put("msg", "达人申请中");
                    resultMap.put("result", false);
                } else {
                    resultMap.put("msg", "您已经是达人");
                    resultMap.put("result", false);
                }
            }else {
                resultMap.put("msg","您的账号有问题");
                resultMap.put("result",false);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 审核达人
     *
     * @param startId
     * @param status
     * @param request
     * @return
     */
    @RequestMapping(value = "/checkStart.json")
    @ResponseBody
    public Map<String, Object> checkStart(
            @RequestParam(value = "startId") long startId,
            @RequestParam(value = "status") int status,   //0.审核未通过 1.审核未通过
            HttpServletRequest request) {

        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Start start = startDao.getStartById(startId);
            AppUser appUser = appUserDao.getUserById(start.getAppUserId());
            if (appUser!=null){
                start.setStatus(status);
                startDao.updateStart(start);
                if (status == 1) {
                    appUser.setIsDR(1);
                    appUserDao.updateUser(appUser);
                }
                resultMap.put("result", true);
            } else {
                resultMap.put("msg","账号异常");
                resultMap.put("result",false);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 达人推荐
     *
     * @param pageNum
     * @param request
     * @return
     */
    @RequestMapping(value = "/startList.json")
    @ResponseBody
    public Map<String, Object> startList(
            @RequestParam(value = "appUserId") long appUserId,
            @RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            List<AppUser> appUserList = appUserDao.getDaRen((pageNum - 1) * rows, rows);
            for (AppUser appUser : appUserList) {
                Focus focus = focusDao.getFocusByIds(appUserId, appUser.getId());
                if (focus == null) {
                    appUser.setIsFocus(0);
                } else {
                    appUser.setIsFocus(1);
                }
            }
            resultMap.put("appUserList", appUserList);
            resultMap.put("result", true);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    public void putObject(String date, String filename, InputStream content,
                          Long size) throws FileNotFoundException {

        // 初始化OSSClient
        OSSClient client = new OSSClient("W6PVM427mSEWlvEz",
                "h7NoXlxcjCqyeOWeuT43LungGmGRSd");

        // 获取指定文件的输入流
        // File file = new File(filePath);
        // InputStream content = new FileInputStream(file);

        // 创建上传Object的Metadata
        ObjectMetadata meta = new ObjectMetadata();

        // 必须设置ContentLength
        meta.setContentLength(size);

        // 上传Object.
        PutObjectResult result = client.putObject("icake", "headImg/" + date
                + "/" + filename, content, meta);

        // 打印ETag
        System.out.println(result.getETag());
    }
}
